package com.tasks.enums;

import java.util.Iterator;
import java.util.LinkedList;
import org.apache.log4j.Logger;
import com.tasks.server.ServerException;

public class Enum {
	
	static Logger logger = Logger.getLogger(Enum.class);
	
	private int value;
	private String code;
	private String text;	
	
	public Enum(int v, String c, String t)
	{
		value = v;
		code = c;
		text = t;
	}
	
	public final int intValue()
	{
		return value;
	}
	
	public final String getCode()
	{
		return code;
	}
	
	public final String getText()
	{
		return text;
	}
	
	public String toString()
	{
		return text;
	}
			
	public static final Enum newInstance(String cls, int value)
	{
		Class<?> classType = getClassName(cls);
		if(classType != null)
		{
			try
			{
				return (Enum)classType.getMethod("valueOf", new Class[]{int.class}).invoke(null, new Object[]{new Integer(value)});
			}
	
			catch (Exception e)
			{
				new ServerException(Enum.class, "newInstance", "Error invoking \"valueOf\" method of enum " + classType.getCanonicalName());
			}
		}
		else 
		{
			new ServerException(Enum.class, "newInstance", "Cannot find enum class for: " + cls);
		}
		return null;
	}
	
	private static Class<?> getClassName(String cls)
	{
		LinkedList<Object[]> enumClasses = new LinkedList<Object[]>();
		enumClasses.add(new Object[]{"PRIORITY", Priority.class});
		enumClasses.add(new Object[]{"LOCATION", Location.class});
		
		for(Iterator<Object[]> i = enumClasses.iterator(); i.hasNext();)
		{
			Object[] o = i.next();
			if(((String)o[0]).compareTo(cls) == 0)
			{
				return (Class<?>) o[1];
			}
		}
		
		return null;
	}	
}
